package com.app.micaihu.view.main.msgcenter.fragment;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.android.volley.VolleyError;
import com.app.micaihu.R;
import com.app.micaihu.app.AppApplication;
import com.app.micaihu.base.BaseOldActivity;
import com.app.micaihu.base.BaseSwipeMenuListFragment;
import com.app.micaihu.base.bean.DataBean;
import com.app.micaihu.bean.message.MsgCenter;
import com.app.micaihu.configure.ActivityRequestCode;
import com.app.micaihu.configure.Config;
import com.app.micaihu.configure.ConfigKeyConstant;
import com.app.micaihu.configure.TypeConstant;
import com.app.micaihu.configure.URIContant;
import com.app.micaihu.listener.HttpListener;
import com.app.micaihu.manager.AppConfigManager;
import com.app.micaihu.manager.UserInforManager;
import com.app.micaihu.utils.HttpUtils;
import com.app.micaihu.view.army.activity.ArmyMessageListActivity;
import com.app.micaihu.view.main.msgcenter.EditorRecommendActivity;
import com.app.micaihu.view.main.msgcenter.MsgCenterListActivity;
import com.app.micaihu.view.main.msgcenter.MsgNoticeListActivity;
import com.app.micaihu.view.main.msgcenter.adapter.MsgCenterAdapter;
import com.app.micaihu.view.set.AliFeedBackActivity;
import com.app.micaihu.view.user.userinfo.activity.AttentionAndFansListActivity;
import com.app.micaihu.view.user.userinfo.activity.WebActivity;
import com.app.utils.swipemenulistview.SwipeMenu;
import com.app.utils.swipemenulistview.SwipeMenuCreator;
import com.app.utils.swipemenulistview.SwipeMenuItem;
import com.app.utils.swipemenulistview.SwipeMenuListView;
import com.app.utils.util.StringUtils;
import com.app.utils.util.ViewSizeUtils;
import com.app.utils.util.osutils.StatusBarUtils;
import com.baidu.mobstat.StatService;
import com.google.gson.reflect.TypeToken;
import com.jeremyliao.liveeventbus.LiveEventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import de.greenrobot.event.EventBus;

/**
 * Created by Guo on 2016/9/26.
 * <p/>
 * <p/>
 * 消息列表的fragment
 */
public class MessageFragment extends BaseSwipeMenuListFragment<MsgCenter> {


    private boolean isFirstLoad = false;

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mPageName = "MessageFragment";
    }

    @Override
    public void onResume() {
        super.onResume();
        if (!isFirstLoad) {
            isFirstLoad = true;
        } else {
            changeData(true);
        }

    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            changeData(true);
        }
    }

    @Override
    protected void configSwiperMenuListView() {
        SwipeMenuCreator creator = new SwipeMenuCreator() {

            @Override
            public void create(SwipeMenu menu) {
                SwipeMenuItem deleteItem = new SwipeMenuItem(activity.getApplicationContext());
                deleteItem.setBackground(R.drawable.swipe_deleteitem_bg);
                deleteItem.setWidth(ViewSizeUtils.dp2px(activity, 60));
                deleteItem.setIcon(R.drawable.common_delete_icon);
                menu.addMenuItem(deleteItem);
            }
        };
        // set creator
        mListView.setMenuCreator(creator);
        // step 2. listener item click event
        mListView.setOnMenuItemClickListener(new SwipeMenuListView.OnMenuItemClickListener() {
            @Override
            public void onMenuItemClick(int position, SwipeMenu menu, int index) {
                switch (index) {
                    case 0://删除当前点击的数据
                        deleteItem(position);

                        break;
                }
            }
        });

        mListView.setOnSwipeListener(swipeListener);

    }

    /**
     * 删除list的item
     *
     * @param position
     */
    private void deleteItem(int position) {
        MsgCenter msgCenter = null;
        if (dataList != null && dataList.size() > position) {
            msgCenter = dataList.get(position);
            if (msgCenter != null) {
                dataList.remove(position);
                //将删除的模块记入本地，无新消息的时候就不显示了
                AppConfigManager.getInstance().writeConfig(ConfigKeyConstant.show_delete_item_ + msgCenter.getType(), false);
            }
        }
        if (mAdapter != null) {
            mAdapter.notifyDataSetChanged();
        }
        if (msgCenter == null) {
            return;
        }
    }


    /**
     * 设定当前的item可否滑动
     */
    SwipeMenuListView.OnSwipeListener swipeListener = new SwipeMenuListView.OnSwipeListener() {
        @Override
        public void onSwipeStart(int position) {
            swipSlide(position);
        }

        @Override
        public void onSwipeEnd(int position) {
        }

        @Override
        public void onDownAction(boolean isOpen) {

        }
    };

    /**
     * 控制当前条目是否可滑动删除
     *
     * @param position
     */
    private void swipSlide(int position) {
        mListView.currentItemCanSwipe(false);
        if (dataList != null && !dataList.isEmpty()) {

            if (position > 0 && position < dataList.size()) {
                MsgCenter msgCenter = dataList.get(position);
                String type = msgCenter.getType();
                if (TextUtils.equals(type, TypeConstant.MSG_NOTICE)
                        || TextUtils.equals(type, TypeConstant.MSG_FEEDBACK)
                        || TextUtils.equals(type, TypeConstant.MSG_RECOMMEND)
//                        || TextUtils.equals(type, TypeConstant.MSG_FANS)
                ) {
                    mListView.currentItemCanSwipe(true);
                }
            }

        }
    }

    @Override
    protected void changeView() {
        super.changeView();
        showFooterView(false);
        if (placeHolderView != null) {
            placeHolderView.removeAllViews();
            LinearLayout title = (LinearLayout) View.inflate(getContext(), R.layout.common_title, null);
            TextView titleStr = (TextView) title.findViewById(R.id.commonTitle);
            titleStr.setText(AppApplication.getInstance().getString(R.string.message_title));
            placeHolderView.addView(title);
        }

        StatusBarUtils.setupStatusBarViewInFragmentLinearLayout(getActivity(), mContentView, R.color.app_theme);
        mContentView.setBackgroundColor(getResources().getColor(R.color.white));
    }

    @Override
    protected void changeData(boolean isRefresh) {
        Map<String, String> params = new HashMap<>();
        if (UserInforManager.getInstance().isLogin()) {
            params.put("uid", UserInforManager.getInstance().getUserInfor().getUid());
        } else {
            params.put("uid", "0");//未登录状态下，传0 or ""，服务器返回不带num的列表数据
        }


        HttpListener<DataBean<ArrayList<MsgCenter>>> msgCenter = new HttpListener<DataBean<ArrayList<com.app.micaihu.bean.message.MsgCenter>>>() {

            @Override
            public void onStart() {
                super.onStart();
                if (dataList == null || dataList.isEmpty()) {
                    setLoadView(LOADING, null);

                }

            }

            @Override
            public void onError(VolleyError error) {
                setLoadView(NO_NET, getString(R.string.neterror));

            }

            @Override
            public void onSuccess(DataBean<ArrayList<MsgCenter>> response) {
                if (!response.noError()) {//失败
                    if (dataList == null || dataList.size() <= 0) {
                        setLoadView(DATAERROR, response.getNnderstoodMsg());
                    } else {
                        setLoadView(LOADSUCES, null);
                    }

                } else {
                    ArrayList<MsgCenter> msgCenterList = response.getData();
                    if (msgCenterList == null || msgCenterList.isEmpty()) {//数据错误 或者 没有数据，
                        setLoadView(DATAERROR, response.getNnderstoodMsg());
                    } else {
                        if (dataList == null) {
                            dataList = new ArrayList<MsgCenter>();
                        } else {
                            dataList.clear();
                        }
                        dataList.addAll(msgCenterList);

                        //版本去重；无适配的将去除掉
//                        removeUselessData();

                        //隐藏 删除掉的item
                        checkDeleteItemShow(dataList);

                        if (mAdapter == null) {
                            mAdapter = new MsgCenterAdapter(dataList, activity);
                            mListView.setAdapter(mAdapter);
                        } else {
                            mAdapter.notifyDataSetChanged();
                        }
                        setLoadView(LOADSUCES, null);

                        flushMsgRed();
                    }
                }
            }
        };
        HttpUtils.addPostCacheRequest(URIContant.MESSAGE_CENTER, new TypeToken<DataBean<ArrayList<MsgCenter>>>() {
        }.getType(), mPageName, params, msgCenter);

    }


    /**
     * 刷新消息总数
     */
    private void flushMsgRed() {
        try {
            int currentMsgCount = 0;
            for (int i = 0; i < dataList.size(); i++) {
                if (dataList.get(i) != null) {
                    currentMsgCount += StringUtils.toInt(dataList.get(i).getNum(), 0);
                }
            }
            LiveEventBus.get(Config.EventBus.flushMsgRed, Integer.class).post(currentMsgCount);
//
//            ArrayList<Object> parms = new ArrayList<>();
//            parms.add("4");
//            parms.add(currentMsgCount);
//            EventBus.getDefault().post(parms);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 去除掉 用户删除过的，并且当前没有消息的条目
     *
     * @param dataList
     */
    private void checkDeleteItemShow(@NonNull List<MsgCenter> dataList) {
        if (!dataList.isEmpty()) {
            for (int i = 0; i < dataList.size(); i++) {
                MsgCenter msgCenter = dataList.get(i);
                if (msgCenter != null) {
                    //先检查 是否删除过
                    boolean isShow = AppConfigManager.getInstance().readConfig(ConfigKeyConstant.show_delete_item_ + msgCenter.getType(), true);
                    if (!isShow) {//如果曾经删除过，检查当前是否有消息
                        int currentMsgNum = StringUtils.toInt(msgCenter.getNum(), 0);
                        if (currentMsgNum <= 0) {
                            dataList.remove(i);
                            i--;
                        }
                    }
                }
            }
        }


    }

    /**
     * 去除掉当前版本无用大数据--2.0.0.1
     * <p/>
     * 当前只支持 评论，@，通知，和反馈
     */
    private void removeUselessData() {
        if (dataList != null && !dataList.isEmpty()) {
            for (int i = 0; i < dataList.size(); i++) {
                MsgCenter msgCenter = dataList.get(i);
                if (msgCenter != null) {
                    String type = msgCenter.getType();
                    if (!TextUtils.equals(type, TypeConstant.MSG_COMMENT)
                            && !TextUtils.equals(type, TypeConstant.MSG_AT)
                            && !TextUtils.equals(type, TypeConstant.MSG_NOTICE)
                            && !TextUtils.equals(type, TypeConstant.MSG_FEEDBACK)) {
                        dataList.remove(i);
                        i--;
                    }
                }

            }
        }


    }


    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

        //防止关闭侧滑的时候 触发点击事件
        if (mListView != null && mListView.getSwipeMenuLayout() == null || dataList == null || dataList.isEmpty())
            return;

        MsgCenter msgCenter = dataList.get(position);
        if (msgCenter == null) return;
        String type = msgCenter.getType();
        Intent intent = new Intent();
        //刷新小红点
        flushRedDot(position, msgCenter);
        switch (type) {
            case TypeConstant.MSG_COMMENT://评论
                StatService.onEvent(activity, "049", "评论我的", 1);// 统计的点击
            case TypeConstant.MSG_AT://@
                StatService.onEvent(activity, "049", "@我的", 1);// 统计的点击
            case TypeConstant.MSG_ZAN://赞
                StatService.onEvent(activity, "049", "收到的赞", 1);// 统计的点击
                if (!UserInforManager.getInstance().isLogin()) {
                    UserInforManager.getInstance().toLoginPage(activity);
                    return;
                }
                intent.putExtra(Config.Extra.PARAMETER1, type);
                intent.setClass(activity, MsgCenterListActivity.class);
                break;
            case TypeConstant.MSG_FANS://粉丝
                StatService.onEvent(activity, "049", "我的粉丝", 1);// 统计的点击
                if (!UserInforManager.getInstance().isLogin()) {
                    UserInforManager.getInstance().toLoginPage(activity);
                    return;
                }
                intent.putExtra(Config.Extra.PARAMETER1, false);
                intent.putExtra(Config.Extra.PARAMETER2, UserInforManager.getInstance().getUserInfor().getUid());
                intent.setClass(activity, AttentionAndFansListActivity.class);
                break;
            case TypeConstant.MSG_NOTICE://通知
                StatService.onEvent(activity, "049", "消息提醒", 1);// 统计的点击
                intent.putExtra(Config.Extra.PARAMETER1, type);
                intent.setClass(activity, MsgNoticeListActivity.class);
                break;
            case TypeConstant.MSG_FEEDBACK://反馈
                intent.setClass(activity, AliFeedBackActivity.class);
                StatService.onEvent(activity, "049", "消息反馈", 1);//统计事件的点击次数
                break;
            case TypeConstant.MSG_RECOMMEND://推荐
                StatService.onEvent(activity, "049", "虎哥推荐", 1);//统计事件的点击次数
                intent.setClass(activity, EditorRecommendActivity.class);
                break;
            case TypeConstant.MSG_SHOP://虎妞小店
                StatService.onEvent(activity, "049", "虎妞小店", 1);//统计事件的点击次数
                intent.setClass(activity, WebActivity.class);
                intent.putExtra("url", msgCenter.getJumpUrl());
                intent.putExtra("title", msgCenter.getName());

                break;
            case TypeConstant.MSG_ARMY://军团消息
                StatService.onEvent(activity, "049", "军团消息", 1);//统计事件的点击次数
                intent.setClass(activity, ArmyMessageListActivity.class);
                break;
            default:
                break;
        }
        intent.putExtra(MsgCenterListActivity.TITLE_NAME, msgCenter.getName());
        if (intent.getComponent() != null) {
            activity.startActivityForResult(intent, ActivityRequestCode.REQEUST_CODE_MSG_DETAIL);
            activity.overridePendingTransition(R.anim.base_slide_right_in, R.anim.base_slide_remain);
        }

    }

    /**
     * 刷新小红点
     *
     * @param position
     * @param msgCenter
     */
    private void flushRedDot(int position, MsgCenter msgCenter) {

        msgCenter.setNum("0");
        dataList.remove(position);
        dataList.add(position, msgCenter);
        mAdapter.notifyDataSetChanged();

        flushMsgRed();
    }


    public List getCurrentData() {
        return dataList;
    }


    //重写滚动监听，防止其加载更多
    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
        //super.onScrollStateChanged(view, scrollState);
    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
        //super.onScroll(view, firstVisibleItem, visibleItemCount, totalItemCount);
    }


}
